package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-26
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {
    /**
     * 登录业务处理
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //先确定用户名或者密码是否为空
        if(loginDto==null|| StringUtils.isBlank(loginDto.getName())||StringUtils.isBlank(loginDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查用户是否存在
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName,loginDto.getName());
        AdUser user = this.getOne(queryWrapper);
        //如果数据等于零就没查到结果
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //如果查到结果进行密码比较
        String s = loginDto.getPassword() + user.getSalt();
        String md5Hex = DigestUtils.md5Hex(s);
        if(!StringUtils.equals(md5Hex,user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //返回user和total
        //去除敏感信息
        Map resultMap = new HashMap();
        user.setPassword("");
        user.setSalt("");
        user.setPhone("");
        resultMap.put("user",user);

        Map claimMaps = new HashMap();
        claimMaps.put("userId",user.getId());
        claimMaps.put("userName",user.getName());
        String token = AppJwtUtil.getToken(claimMaps);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
